// pages/index/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        show: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const _this = this
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.camera']) {
                // 用户已经授权
                _this.setData({
                    isAuth: true
                })
                } 
                else {
                    // 用户还没有授权，向用户发起授权请求
                    wx.authorize({
                        scope: 'scope.camera',
                        success() { // 用户同意授权
                            _this.setData({
                                isAuth: true
                            })
                        },
                        fail() { // 用户不同意授权
                            _this.openSetting().then(res => {
                                _this.setData({
                                isAuth: true
                                })
                            })
                        }
                    })
                }
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },


    // 打开授权设置界面
  openSetting() {
    const _this = this
    let promise = new Promise((resolve, reject) => {
      wx.showModal({
        title: '授权',
        content: '请先授权获取摄像头权限',
        success(res) {
          if (res.confirm) {
            wx.openSetting({
              success(res) {
                if (res.authSetting['scope.camera']) { // 用户打开了授权开关
                  resolve(true)
                } 
                else { // 用户没有打开授权开关， 继续打开设置页面
                  _this.openSetting().then(res => {
                    resolve(true)
                  })
                }
              },
              fail(res) {
                console.log(res)
              }
            })
          } 
          else if (res.cancel) {
            _this.openSetting().then(res => {
              resolve(true)
            })
          }
        }
      })
    })
    return promise;
  },


  takePhoto() {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath,
          show: true
        })
        this.changeBase64()
        console.log(res.tempImagePath)
        wx.previewImage({
          current: res.tempImagePath, // 当前显示图片的http链接
          urls: [res.tempImagePath] // 需要预览的图片http链接列表
        })
      }
    })
  },

  // 选择图片
  choose(){
    var that=this
    wx.chooseMedia({
        success(res){
            that.setData({
                loadSrc:res.tempFiles[0].tempFilePath
            })
            console.log(res.tempFiles[0].tempFilePath)
        },
        fail(res){
        },
        complete(res){
        }
    })
  },

  save(){
    var that=this;
    wx.saveImageToPhotosAlbum({
        filePath:that.data.src,
        success(res){
            console.log('save success!!!');
        }
    })
  },

  /**
   * 转base64
   */
  changeBase64(){
    wx.getFileSystemManager().readFile({
      filePath: this.data.src,
      encoding: 'base64',
      success: src => {
        // this.setData({
        //   // src:src.data
        // })
        this.postImg(src.data)
        console.log("123456")
      }
    })
  },

  /**
   * 绘制线条
   */
  drawLine(){
    const {results} = this.data
    var index = 5
    results.forEach(element => {
      let name = element.name
      let score = element.score
      let height = element.location.height
      let width = element.location.width
      let left = element.location.left
      let top = element.location.top
      this.data.rect = []
      const rect = this.data.rect.concat({
        "name":name,
        "score":score.toFixed(2),
        "height":height*2/5+2,
        "width":width*2/5+2,
        "left":(left*2+150)/5+100,
        "top":top*2/5+2,
        "index":index
        // 下面是电脑模式
        // "name":name,
        // "score":score.toFixed(2),
        // "height":height*2,
        // "width":width*2,
        // "left":left*2+150,
        // "top":top*2,
        // "index":index
      })
      this.setData({
        rect
      })
      index+=1
    });
  },

  /**
   * 发送请求获取结果
   */
  postImg(base64){
    // console.log(base64)
    const that = this
    wx.request({
      url: 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/detection/sedfsdf?access_token=24.0b1d75998dc3eeb84fad04a6a16b152f.2592000.1673166657.282335-28062499', // 这是羽毛球的
    //   url:'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/detection/zzl_log?access_token=24.6c3c35c516d6a313860e4235292818fc.2592000.1673327362.282335-28965799',    // 口罩检测的
      method: 'POST',
      data:{
        "threshold":0.3,
        "image":base64
      },
      success: function(res) {
        if(res.statusCode == 200){
          const {results} = res.data
          that.setData({   
            results
          })
          console.log(results)
          that.drawLine()
        }
      },
      fail: function() {
        wx.showToast({
          title: "网络连接失败",
          duration: 3000
        })
      },
    })
  },
  reload(){
      this.setData({
          show: false
      })
  }
})